package org.oslims.client.uicomponents;

import java.util.Date;

import org.oslims.domain.ParameterResult;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;

public class MeasurementTimeCell extends AbstractCell<ParameterResult> {

	@Override
	public boolean consumesEvents() {
		return true;
	}

	@Override
	public Object onBrowserEvent(Element parent, ParameterResult value, Object viewData, NativeEvent event, ValueUpdater<ParameterResult> valueUpdater) {

		if (valueUpdater != null && "change".equals(event.getType())) {
			InputElement input = parent.getFirstChild().cast();

			Date t;

			try {
				t = DateTimeFormat.getShortDateTimeFormat().parse(input.getValue());
				value.setMeasuredAt(t);
			} catch (IllegalArgumentException e) {
				Window.alert("Date is not in a valid format");
				GWT.log(e.getMessage());
				value.setMeasuredAt(new Date());
			}
			valueUpdater.update(value);
		}

		return viewData;
	}

	@Override
	public void render(ParameterResult value, Object viewData, StringBuilder sb) {

		if (!value.getState().equals("In Analyzing")) {
			sb.append(DateTimeFormat.getShortDateTimeFormat().format(value.getMeasuredAt()));
			return;
		}

		sb.append("<input type='text'");
		if (value.getMeasuredAt() != null) {
			sb.append(" value='" + DateTimeFormat.getShortDateTimeFormat().format(value.getMeasuredAt()) + "'");
		} else {
			sb.append(" value='" + DateTimeFormat.getShortDateTimeFormat().format(new Date()) + "'");
		}
		sb.append("></input>");
	}

}
